import React, { useState } from 'react';
import { Form, Input, Button, Modal, Descriptions } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import columnsData, { columnsDataType } from './data'
import { getMerchantList, getMerchantDetailsInfo, frozenMerchant, unFrozenMerchant } from './service'
import TableTitle from '../../../components/TableTitle'
// 页面跳转
import { Link, history } from 'umi';

export default () => {
  const { TextArea } = Input;
  // 查看模态框控制
  const [isCheckDetailInfoModal, setIsCheckDetailInfoModal] = useState(false);
  // 冻结模态框控制
  const [isFrozenModal, setIsFrozenModal] = useState(false);
  // 储存当前操作数据
  const [merchantDetailInfo, setMerchant] = useState<columnsDataType & { reason?: string } | undefined>(undefined)
  // 确认 获取原因表单
  const reasonFormRef: any = React.createRef();

  // 查看
  const check = async (custNo: string) => {
    console.log(custNo);

    // 传入商户的信息
    const merchantDetailInfo = await getMerchantDetailsInfo({ custNo })
    console.log('merchantDetailInfo', merchantDetailInfo);

    setMerchant(merchantDetailInfo.body)
    setIsCheckDetailInfoModal(true)
  }

  // 冻结
  const frozenInfo = (record: any) => {
    setMerchant(record)
    setIsFrozenModal(true)
  }

  // 处理冻结
  const handleFrozenInfoOk = () => {
    // 表单验证
    reasonFormRef.current.validateFields().then(async () => {
      // 获取解冻处理表单的值
      var reponse = reasonFormRef.current?.getFieldsValue()
      console.log('111!!', reponse);
      reponse.custNo = merchantDetailInfo?.custNo
      console.log('2222!!', reponse);

      merchantDetailInfo?.custStatus === '0' ?
        await frozenMerchant(reponse) :
        await unFrozenMerchant(reponse).then((res) => {
          console.log(res);
        })
      // 重置表单
      reasonFormRef.current.resetFields();
      // 表格重刷新
      actionRef.current?.reload()
      // 关闭模态框
      setIsFrozenModal(false)
    }).catch(() => { })
  }

  // 当前行的数据保存，传递到下一个页面进行使用
  const saveDiscountConfigure = (record: columnsDataType) => {
    console.log(record);

    history.push({
      pathname: '/discount-configuration',
      state: {
        custNo: record.custNo
      },
    })
  }

  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) =>
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      {/* <li>
        <a onClick={() => { check(record.custNo) }}>查看</a>
        <em className="ant-list-item-action-split"></em>
      </li> */}
      <li>
        <a onClick={() => saveDiscountConfigure(record)}>
          折扣配置
        </a>
        <em className="ant-list-item-action-split"></em>
      </li>
      {
        record.custStatus !== '0' && record.custStatus !== '1' ? '' :
          <li>
            <a onClick={() => { frozenInfo(record) }}
              className="ant-dropdown-trigger">
              {record.custStatus === '0' ? "冻结" : record.custStatus === '1' ? '解冻' : ''}
            </a>
          </li>
      }
    </ul>

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? item.render = actionRender : undefined
  });

  // Table action 的引用，便于自定义触发
  const actionRef = React.useRef<ActionType>();

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<TableTitle title='商户信息' />}
        scroll={{ x: 900 }}
        actionRef={actionRef}
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={
          async params => {
            console.log(params);
            let data = await getMerchantList({ ...params, pageNum: params.current })
            console.log('😒', data);
            const result = {
              data: data.body.list,
              total: data.body.total,
            }
            return result;
          }
        }
        rowKey="custNo"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
      />
      {/* 查看模态框 */}
      <Modal
        title="商户信息"
        width={1000}
        centered
        footer={<Button type="primary" htmlType="submit" onClick={() => setIsCheckDetailInfoModal(false)}>
          确认
        </Button>}
        visible={isCheckDetailInfoModal}
        onCancel={() => setIsCheckDetailInfoModal(false)}
      >
        <Descriptions
          column={{ xxl: 4, xl: 4, lg: 4, md: 3, sm: 2, xs: 1 }}
        >
          <Descriptions.Item label="商户名">{merchantDetailInfo?.custName}</Descriptions.Item>
          <Descriptions.Item label="商户号">{merchantDetailInfo?.custNo}</Descriptions.Item>
          <Descriptions.Item label="邮箱">{merchantDetailInfo?.email}</Descriptions.Item>
          <Descriptions.Item label="商户状态">
            {
              merchantDetailInfo?.custStatus === '0' ? '正常' :
                merchantDetailInfo?.custStatus === '1' ? '冻结' :
                  merchantDetailInfo?.custStatus === '2' ? '注销' :
                    merchantDetailInfo?.custStatus === '3' ? '未激活' : null
            }
          </Descriptions.Item>
          <Descriptions.Item label="注册日期">{merchantDetailInfo?.openDate}</Descriptions.Item>
          <Descriptions.Item label="电话">{merchantDetailInfo?.mobile}</Descriptions.Item>
          <Descriptions.Item label="折扣编码">{merchantDetailInfo?.disctNo}</Descriptions.Item>
          {
            merchantDetailInfo?.custStatus === '1' ?
              <Descriptions.Item label="冻结原因">{merchantDetailInfo?.reason}</Descriptions.Item> :
              null
          }
        </Descriptions>
      </Modal>
      {/* 冻结解冻模态框 */}
      <Modal
        title={
          <div>
            <span>商户名: {merchantDetailInfo?.custName}</span>
            <span style={{ marginLeft: 20 }}>商户号: {merchantDetailInfo?.custNo}</span>
          </div>
        }
        centered
        visible={isFrozenModal}
        onOk={handleFrozenInfoOk}
        onCancel={() => setIsFrozenModal(false)}
      >
        <Form
          name="basic"
          ref={reasonFormRef}
          wrapperCol={{ span: 24 }}
          autoComplete="off"
        >
          <Form.Item
            key="reason"
            name="reason"
            rules={[{
              required: true,
              whitespace: true,
              message: '请填写原因'
            }]}
          >
            <TextArea maxLength={225} rows={4} placeholder="请输入原因" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};